package prv.pursuivant.core.impl;

import java.util.Date;

import prv.pursuivant.core.AchievType;
import prv.pursuivant.core.AchievTypesTree;
import prv.pursuivant.core.Achievement;
import prv.pursuivant.core.AchievementCalculator;
import prv.pursuivant.core.AchievementStatus;
import prv.pursuivant.core.AllAchievements;

import com.google.inject.Inject;

public class AchievementCalculatorImpl implements AchievementCalculator {

	private final AchievTypesTree tree;
	private final AllAchievements achievements;

	@Inject
	public AchievementCalculatorImpl(AchievTypesTree tree,
			AllAchievements achievements) {
		this.tree = tree;
		this.achievements = achievements;
	}

	@Override
	public AchievementStatus getAchievementStatus(String toonName,
			String achievTypeId, Date when) {

		AchievType achievType = tree.findAchievTypeById(achievTypeId);
		Achievement achiev = achievements.get(toonName, achievTypeId);
		Date lastCritDate = null;

		int all = achievType.getCriteria().size();
		int done = 0;
		for (String critId : achievType.getCriteria()) {
			if (achievements.contains(toonName, critId)) {
				final Date critDate = achievements.get(toonName, critId)
						.getDate();
				if (!critDate.after(when)) {
					if (lastCritDate == null || lastCritDate.before(critDate))
						lastCritDate = critDate;
					done++;
				}
			}
		}

		Date date = (achiev == null || achiev.getDate().after(when)) ? null
				: achiev.getDate();

		return new AchievementStatusImpl(date, lastCritDate, done, all);
	}
}
